package com.lili.collection.core.runner.stage;

import com.lili.collection.core.config.InputConfig;
import com.lili.collection.core.context.PipeContext;
import com.lili.collection.core.context.StageContext;
import com.lili.collection.core.event.StageEvent;
import com.lili.collection.core.plugins.InputPlugin;
import com.lili.collection.core.runner.result.RunnerResult;
import lombok.Getter;
import lombok.extern.slf4j.Slf4j;

/**
 * 通用输入Runner
 *
 * @author lili
 * @date 2023/3/7 11:18
 */
@Slf4j
public class GenericInputRunner extends AbstractStageRunner {

    private InputPlugin<InputConfig> plugin;

    @Getter
    private PipeContext pipeContext;
    private RunnerResult inputRunnerResult;

    public GenericInputRunner(PipeContext pipeContext) {
        this.pipeContext = pipeContext;
        this.inputRunnerResult = new RunnerResult();
    }

    @Override
    public RunnerResult getRunnerResult() {
        return this.inputRunnerResult;
    }

    @Override
    public void run() {
        ensurePlugin();
        StageContext stageContext = this.plugin.execute();
        this.getPipeContext().getExchangeStageContext().put(StageType.Input, stageContext);
        triggerStageEvent(StageEvent.STAGE_CONTEXT_CHANGE, this.getStageType(), stageContext);
    }

    @Override
    public StageType getStageType() {
        return StageType.Input;
    }

    @Override
    public void dispose() {
        if (this.plugin != null)
            this.plugin.dispose();
    }

    @Override
    public void pause() {

    }

    @Override
    public void resume() {

    }

    @Override
    public void stop() {
        this.dispose();
    }

    private void ensurePlugin() {
        if (this.plugin != null) return;
        InputConfig inputConfig = this.pipeContext.getContext().getInputConfig();
        this.plugin = inputConfig.getPlugin();
        this.plugin.setRunnerResult(this.inputRunnerResult);
        this.plugin.init(inputConfig);
    }
}
